package com.smcdd.cdb.dbo.cdb_dbo.ui.activity;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.smcdd.cdb.dbo.cdb_dbo.R;
import com.smcdd.cdb.dbo.cdb_dbo.service.entity.LocationBean;
import com.smcdd.cdb.dbo.cdb_dbo.service.presenter.NetInPresenter;
import com.smcdd.cdb.dbo.cdb_dbo.service.view.INetInAc;
import com.smcdd.cdb.dbo.cdb_dbo.ui.base.BaseActivity;
import com.smcdd.cdb.dbo.cdb_dbo.ui.utils.DemoUtils;
import com.smcdd.cdb.dbo.cdb_dbo.ui.utils.ObtainUdis;
import com.tencent.map.geolocation.TencentLocation;
import com.tencent.map.geolocation.TencentLocationListener;
import com.tencent.map.geolocation.TencentLocationManager;
import com.tencent.map.geolocation.TencentLocationRequest;
import com.tencent.map.geolocation.TencentPoi;

import java.util.List;

/**
 * 作者：Administrator on 2017/6/21 11:12
 * 邮箱：zhanghuaiha@gmail.com
 *  激活设备
 */

public class NetInActivity extends BaseActivity<INetInAc,NetInPresenter> implements INetInAc,TencentLocationListener {
    private ImageView back;
    private TextView net_id,net_name,net_save,net_number,net_type;
    private EditText net_remarks,net_user,net_num;
    private static final int REQUEST_SEARCH_CODE = 1;
    private String alias;
    private int device_type;
    private String udid;
    private String id;
    private LinearLayout paper;
    private TencentLocationManager mLocationManager;

    @Override
    public void initView() {
        if (Build.VERSION.SDK_INT >= 23) {
            String[] permissions = {
                    Manifest.permission.ACCESS_COARSE_LOCATION,
                    Manifest.permission.READ_PHONE_STATE,
                    Manifest.permission.WRITE_EXTERNAL_STORAGE
            };

            if (checkSelfPermission(permissions[0]) != PackageManager.PERMISSION_GRANTED)
            {
                requestPermissions(permissions, 0);
            }
        }
        mLocationManager = TencentLocationManager.getInstance(this);
        // 设置坐标系为 gcj-02, 缺省坐标为 gcj-02, 所以通常不必进行如下调用
        // mLocationManager.setCoordinateType(TencentLocationManager.COORDINATE_TYPE_GCJ02);
        startLocation();


        back = (ImageView) findViewById(R.id.net_back);
        net_id = (TextView) findViewById(R.id.net_id);
        net_name = (TextView) findViewById(R.id.net_name);
        net_save = (TextView) findViewById(R.id.net_save);
        net_type = (TextView) findViewById(R.id.net_type);
        net_number = (TextView) findViewById(R.id.net_number);
        net_remarks = (EditText) findViewById(R.id.net_remarks);
        net_user = (EditText) findViewById(R.id.net_user);
        net_num = (EditText) findViewById(R.id.net_num);
        paper = (LinearLayout) findViewById(R.id.paper);
    }


    // 响应点击"开始"
    public void startLocation() {
        // 创建定位请求
        TencentLocationRequest request = TencentLocationRequest.create()
                .setInterval(5000) // 设置定位周期
                .setAllowGPS(true)  //当为false时，设置不启动GPS。默认启动
                .setAllowIndoorLocation(true)  //设置启动室内定位，默认不启动
                .setQQ("10001")
                .setRequestLevel(TencentLocationRequest.REQUEST_LEVEL_ADMIN_AREA); // 设置定位level

        // 开始定位
        mLocationManager.requestLocationUpdates(request, this);

        Log.e("mappp", DemoUtils.toString(mLocationManager.getCoordinateType()));
    }


    @Override
    public void initData() {
        alias = getIntent().getStringExtra("alias");
        device_type = getIntent().getIntExtra("device_type",1);
        udid = ObtainUdis.getUDID(NetInActivity.class);
        net_id.setText(alias);
        switch (device_type) {
            //设备类型 1、WiFi 3、蓝牙 4、密码 5、纸巾机
            case 1:
                net_type.setText("wifi");
                paper.setVisibility(View.GONE);
                break;
            case 2:
                break;
            case 3:
                break;
            case 4:
                net_type.setText("密码");
                paper.setVisibility(View.GONE);
                break;
            case 5:
                net_type.setText("纸巾机");
                paper.setVisibility(View.VISIBLE);
                break;
            default:
                net_type.setText("wifi");
                paper.setVisibility(View.GONE);
                break;
        }
        mPresenter.loadContacts(udid,alias);
    }

    @Override
    public void initListener() {

        net_save.setOnClickListener(v -> {
            String remarks = net_remarks.getText().toString().trim();
            String user = net_user.getText().toString().trim();
            String num = net_num.getText().toString().trim();
            if (TextUtils.isEmpty(remarks)) {
                remarks = "";
            }
            if (TextUtils.isEmpty(user)) {
                user = "";
            }
            if (TextUtils.isEmpty(user)) {
                num = "";
            }
            if (locationBean != null) {
                mPresenter.loadData(alias,udid,id,user,remarks,locationBean.getLat()+"",locationBean.getLog()+"",num);
            }else {
                mPresenter.loadData(alias,udid,id,user,remarks,"","",num);
            }



        });
        net_name.setOnClickListener(v -> {
            Intent intent = new Intent(NetInActivity.this,QueryActivity.class);
            startActivityForResult(intent,REQUEST_SEARCH_CODE);
        });
        back.setOnClickListener(v -> finish());
        net_remarks.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
              //  Log.e("aaa",s.length()+"");
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
               // Log.e("bbbbb",s.length()+"");
            }

            @Override
            public void afterTextChanged(Editable s) {
               // Log.e("cccc",s.length()+"");
                net_number.setText(s.length()+"/100");

            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == REQUEST_SEARCH_CODE) {
            if (data != null) {
                id = data.getStringExtra("id");
                String name = data.getStringExtra("name");
                net_name.setText(name);
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mLocationManager.removeUpdates(this);
    }

    @Override
    protected NetInPresenter createPresenter() {
        return new NetInPresenter(this);
    }

    @Override
    protected int provideContentViewId() {
        return R.layout.activity_net_in;
    }

    @Override
    public EditText getET() {
        return net_user;
    }

    @Override
    public EditText getRemark() {
        return net_remarks;
    }

    @Override
    public EditText getNum() {
        return net_num;
    }

    @Override
    public TextView getTV() {
        return net_name;
    }

    @Override
    public TextView getType() {
        return net_type;
    }

    //定位
    @Override
    public void onLocationChanged(TencentLocation location, int error, String s) {
        LocationBean locationBean = null;
        if (error == TencentLocation.ERROR_OK) {
            // 定位成功
            locationBean = toString(location, TencentLocationRequest.REQUEST_LEVEL_ADMIN_AREA);
        } else {
            // 定位失败
            String msg = "定位失败: " + s;
            locationBean = new LocationBean();
            locationBean.setName(msg);
        }
        updateLocationStatus(locationBean);
    }



    @Override
    public void onStatusUpdate(String s, int i, String s1) {

    }

    private LocationBean locationBean;

    private void updateLocationStatus(LocationBean locationBean) {
        mLocationManager.removeUpdates(this);
        this.locationBean = locationBean;
//      ininData(locationBean);
        Log.e("map",locationBean.getName());

    }


    // ===== util method
    private static LocationBean toString(TencentLocation location, int level) {
        StringBuilder sb = new StringBuilder();
        if (location.getLatitude() != 0.0 && location.getLongitude() != 0.0) {
            LocationBean locationBean = new LocationBean();
            locationBean.setLat(location.getLatitude());
            locationBean.setLog(location.getLongitude());
            locationBean.setName("获取定位成功");
            return locationBean;
        }

        sb.append("latitude=").append(location.getLatitude()).append(",");
        sb.append("longitude=").append(location.getLongitude()).append(",");
        sb.append("altitude=").append(location.getAltitude()).append(",");
        sb.append("accuracy=").append(location.getAccuracy()).append(",");
        sb.append("indoorBuildingId=").append(location.getIndoorBuildingId()).append(",");
        sb.append("indoorBuildingFloor=").append(location.getIndoorBuildingFloor()).append(",");

        switch (level) {
            case TencentLocationRequest.REQUEST_LEVEL_GEO:
                break;

            case TencentLocationRequest.REQUEST_LEVEL_NAME:
                sb.append("name=").append(location.getName()).append(",");
                sb.append("address=").append(location.getAddress()).append(",");
                break;

            case TencentLocationRequest.REQUEST_LEVEL_ADMIN_AREA:
            case TencentLocationRequest.REQUEST_LEVEL_POI:
            case 7:
                sb.append("nation=").append(location.getNation()).append(",");
                sb.append("province=").append(location.getProvince()).append(",");
                sb.append("city=").append(location.getCity()).append(",");
                sb.append("district=").append(location.getDistrict()).append(",");
                sb.append("town=").append(location.getTown()).append(",");
                sb.append("village=").append(location.getVillage()).append(",");
                sb.append("street=").append(location.getStreet()).append(",");
                sb.append("streetNo=").append(location.getStreetNo()).append(",");

                if (level == TencentLocationRequest.REQUEST_LEVEL_POI) {
                    List<TencentPoi> poiList = location.getPoiList();
                    int size = poiList.size();
                    for (int i = 0, limit = 3; i < limit && i < size; i++) {
                        sb.append("\n");
                        sb.append("poi[" + i + "]=")
                                .append(toString(poiList.get(i))).append(",");
                    }
                }

                break;

            default:
                break;
        }

        return null;
    }

    private static String toString(TencentPoi poi) {
        StringBuilder sb = new StringBuilder();
        sb.append("name=").append(poi.getName()).append(",");
        sb.append("address=").append(poi.getAddress()).append(",");
        sb.append("catalog=").append(poi.getCatalog()).append(",");
        sb.append("distance=").append(poi.getDistance()).append(",");
        sb.append("latitude=").append(poi.getLatitude()).append(",");
        sb.append("longitude=").append(poi.getLongitude()).append(",");
        return sb.toString();
    }
}
